const path = require('path');
const fs = require('fs');
const glob = require('globby');
const SpritesmithPlugin = require('webpack-spritesmith');
const spritedict = {},
spriteConf = [];
const isProd = process.env.NODE_ENV === 'production';
const addHash = isProd ? '.[hash:5]': '';
const cwd = process.cwd();
const staticRoot = `${cwd}/src/static`;
glob.sync(path.join(staticRoot, 'icon/**/*')).forEach((dirname) => {
  const parsed = path.parse(dirname);
  const name = parsed.name;
  const dir = parsed.dir;
  let type = parsed.dir.split('/').reverse()[0];
  const stat = fs.statSync(dirname);
  type = type === 'icon' ? 'common' : type;
  if (!stat.isDirectory() || type !== 'common') {
    const item = {
      name,
      dirname
    };
    if (spritedict[type]) {
      spritedict[type].data.push(item);
    } else {
      spritedict[type] = {
        dir,
        type,
        data: [item]
      };
    }
  }
});
for (const key in spritedict) {
  const item = spritedict[key];
  const name = item.type;
  if (item.data.length > 0) {
    spriteConf.push(new SpritesmithPlugin({
      src: {
        cwd: item.dir,
        glob: '*.png'
      },
      target: {
        image: path.join(staticRoot, `images/sprite/${name}${addHash}.png`),
        css: [
          [path.join(staticRoot, `style/icon/_${name}.scss`), {
            format: 'spriteTemplate',
            spritesheetName: name
          }]
        ]
      },
      retina: '@2x',
      apiOptions: {
        cssImageRef: `#{$staticRoot}images/sprite/${name}${addHash}.png`
      },
      customTemplates: {
        spriteTemplate_retina: spriteTemplateRetina
      },
      spritesmithOptions: {
        padding: 4,
        imgOpts: {
          quality: 75
        }
      }
    }));
  }
}
module.exports = spriteConf;

/**
 * @function getIconName 获取icon名称
 * @param {object} spriteItem // 雪碧选项
 */
function getStyleName(spriteItem) {
  const parsed = path.parse(spriteItem.source_image);
  const dirs = parsed.dir.split('/');
  let dir = dirs[dirs.length - 1];
  dir = dir === 'icon' ? '' : '-' + dir;
  return `.icon${dir}-${spriteItem.name}`;
}

/**
 * @function getNormalStyles 图片css精灵模板
 * @param {Array} sprites 雪碧图
 * @param {Number} scale css样式字符串
 * @return {Object}
 * {
 *  icons: [], // 样式类名
 *  styles: '' // 样式字符串
 * }
 */
function getNormalStyles(sprites, scale) {
  let styles = '';
  const icons = [];
  for (let i = 0; i < sprites.length; i++) {
    const spriteItem = sprites[i];
    const iconName = getStyleName(spriteItem);
    if (icons) {
      icons.push(iconName);
    }
    let offsetX = parseInt(spriteItem.offset_x) * scale;
    let offsetY = parseInt(spriteItem.offset_y) * scale;
    let width = parseInt(spriteItem.width) * scale;
    let height = parseInt(spriteItem.height) * scale;
    styles += `\n${iconName}{width:(${width}px);height:(${height}px);background-position:(${offsetX}px) (${offsetY}px);}`;
  }
  return {
    icons,
    styles
  };
}

/**
 * @function spriteTemplateRetina 图片css精灵模板
 * @param {Object} spriteData
 * @return {String} css样式字符串
 */
function spriteTemplateRetina(spriteData) {
  let spriteSheet = spriteData.spritesheet;
  let sprites = spriteData.sprites;
  const { icons, styles } = getNormalStyles(sprites, 1); // 设置公共样式
  return `
  ${icons.join(',')}{
    display:inline-block;box-sizing:border-box;background-image:url("${spriteSheet.image}");background-repeat: no-repeat;
  }\n
  ${styles}\n
  @media(-webkit-min-device-pixel-ratio:2),(min-resolution: 192dpi){
  ${icons.join(',')}{
    display:inline-block;background-repeat:no-repeat;background-image:url("${spriteData.retina_spritesheet.image}");
    background-size:(${spriteSheet.width}px) (${spriteSheet.height}px);
  }}`;
}
